#pragma once
#ifndef _RENDERABLEVERTEXS
#define _RENDERABLEVERTEXS

#include <d3dx9.h>
#include "Base.h"
#include "GraphicsManager.h"
#include <assert.h>

class CGraphicsManager;

class CRenderableVertexs
{
protected:
	LPDIRECT3DVERTEXBUFFER9 m_VB;
	LPDIRECT3DINDEXBUFFER9 m_IB;
	size_t m_IndexCount, m_VertexCount;
public:
	CRenderableVertexs(){}
	virtual ~CRenderableVertexs() 
	{
		CHECKED_RELEASE(m_VB);
		CHECKED_RELEASE(m_IB);
	}
	virtual bool Render(CGraphicsManager *RM) = 0;
	virtual inline size_t GetFacesCount() {return m_IndexCount;}
	virtual inline size_t GetVertexsCount() {return m_VertexCount;}
	virtual inline unsigned short GetVertexType() const = 0;
	virtual inline size_t GetVertexSize() = 0;
	virtual inline size_t GetIndexSize() = 0;
};

template<class T> //la clase T tiene q ser un tipo de vertex
class CIndexedVertexs : public CRenderableVertexs
{
protected:
	inline size_t GetVertexSize() {return sizeof(T);}
	inline size_t GetIndexSize() {return sizeof(unsigned short);}

public:
	CIndexedVertexs(CGraphicsManager *RM, void *VertexAddress, void *IndexAddres, size_t	VertexCount, size_t IndexCount)
	{
		m_VertexCount=VertexCount;
		m_IndexCount=IndexCount;
		
		//creo el vertex buffer
		if(FAILED( CORE->GetGraphicsManager()->GetDevice()->CreateVertexBuffer( m_VertexCount*GetVertexSize(),0 /*Usage*/, T::GetFVF(), D3DPOOL_DEFAULT,&m_VB , NULL ) ) ) assert(E_FAIL);
		
		//copio la info de la memoria ram a la vram
		VOID* pVertices; //parametro de salida de la siguiente funcion q me indica locacion de memoria disponible en la vram para pegar los datos

		if(FAILED(m_VB->Lock(0, GetVertexSize()*m_VertexCount, (VOID**)&pVertices, 0 ) ) )assert(E_FAIL) ;


		memcpy(pVertices, VertexAddress, GetVertexSize()*m_VertexCount);
		m_VB->Unlock();
		//-----------------------------------------------------------------------------------------------
		
		if(FAILED( CORE->GetGraphicsManager()->GetDevice()->CreateIndexBuffer( m_IndexCount*GetIndexSize(),0 /*Usage*/, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &m_IB, NULL ) ) ) assert(E_FAIL);		
		if(FAILED(m_IB->Lock(0, GetIndexSize()*m_IndexCount, (VOID**)&pVertices, 0 ) ) ) assert(E_FAIL);

		memcpy(pVertices, IndexAddres, GetIndexSize()*m_IndexCount);
		m_IB->Unlock();
	
	}
	//CIndexedVertxs(){}
	~CIndexedVertexs()
	{
	}
	virtual bool Render(CGraphicsManager *RM)
	{
		RM->GetDevice()->SetFVF(T::GetFVF());
		RM->GetDevice()->SetStreamSource(0, m_VB, 0, sizeof(T));
		RM->GetDevice()->SetIndices(m_IB);
		RM->GetDevice()->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_VertexCount, 0, m_IndexCount);
		return true;
	}
	virtual inline unsigned short GetVertexType() const {return T::GetVertexType();}
};




#endif
